package org.itboys.manager;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.itboys.fuzion.constant.FuzionConstants;
import org.itboys.fuzion.entity.FuzionMember;
import org.itboys.fuzion.mysql.orm.FuziongMemberStatistics;
import org.itboys.fuzion.mysql.service.FuziongMemberStatisticsService;
import org.itboys.fuzion.service.FuzionMemberService;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.page.PageQueryParam;
import org.itboys.mongodb.utils.query.AceUtils;
import org.itboys.mongodb.utils.query.PageQueryUtils;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.itboys.seller.entity.Seller;
import org.itboys.seller.service.SellerService;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;

/**
 * 会员和店铺之间的关系
 * @author weisky
 *
 * 2016年4月12日
 */
@Service
public class SellerMemberService {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private SellerService sellerService;
	@Autowired
	private FuzionMemberService fuzionMemberService;
	@Autowired
	private FuziongMemberStatisticsService fuziongMemberStatisticsService;
	
	/**
	 * 创建一个店铺的同时，为他生成一个会员；这个会员代表着这个店铺  方便后面的佣金计算
	 * @param seller
	 * @param logos
	 * @param mainImgs
	 * @return
	 */
	public boolean addSellerAndCreateMember(Seller seller, MultipartFile logos, MultipartFile mainImgs){
		long tempSellerId = 0l;
		try{
			tempSellerId = seller.getId();
			boolean resu = sellerService.insert(seller, logos, mainImgs);
			if(!resu){//对店铺的操作失败
				return false;
			}
			
			if(tempSellerId == 0){//新增一个店铺
				//先判断数据库中是否已经存在这个会员  若没有这个会员  再添加
				//一个微信账号只能生成一个会员类型是99的店铺会员
				Map<String, Object> sellerMember = Maps.newHashMapWithExpectedSize(2);
				sellerMember.put("weixinId", seller.getWeixinId());
				sellerMember.put("type", FuzionConstants.Seller.SELLER_SELF_MEMBER);
				List<FuzionMember> fm = fuzionMemberService.list(sellerMember);
				if(fm.isEmpty()){
					FuzionMember fmember = new FuzionMember();
					fmember.setLogo(seller.getLogo());
					fmember.setNickname(seller.getName());
					fmember.setUsername(seller.getName());
					fmember.setRecLevel(FuzionConstants.TYPE_ZERO);
					fmember.setSellerId(seller.getId());
					fmember.setType(FuzionConstants.Seller.SELLER_SELF_MEMBER);
					fmember.setWeixinId(seller.getWeixinId() != null?seller.getWeixinId().toString() : "");
					fuzionMemberService.save(fmember);
					fmember.setPath(FuzionConstants.Seller.SELLER_MEMBER_PATH + fmember.getId() + FuzionConstants.Seller.SELLER_MEMBER_PATH );
					fmember.setRecId(fmember.getId());//推荐人是他自己
					fuzionMemberService.update(fmember);
					logger.info("创建店铺自己的会员成功：FuzionMember=" + JSON.toJSONString(fmember));
					
					//初始化店铺的会员收益信息
					//区分店铺会员和普通会员的区别：  店铺会员：memberId=0&&sellerId!=0  普通会员：memberId！=0&&sellerId!=0
					FuziongMemberStatistics fms = new FuziongMemberStatistics();
					fms.setMemberId(0L);
					fms.setScoreId(0L);
					fms.setTotalMoney(0);
					fms.setWithdrawTotalMoney(0);
					fms.setNowTotalMoney(0);
					fms.setEnergyBean(0);
					fms.setBuyCount(0);
					fms.setNowEnergyBean(0);
					fms.setDynamicIncome(0);
					fms.setStaticIncome(0);
					fms.setSellerId(fmember.getSellerId());
					fms.setPlayNum(0);
					fuziongMemberStatisticsService.insert(fms);
				}
				
			}
			return true;
		}catch(Exception e){
			e.printStackTrace();
			if(tempSellerId == 0){
				sellerService.dele(seller.getId());//如果创建店铺自己的会员失败，就把刚刚新增的店铺信息删除
			}
			logger.error("SellerMemberService.addSellerAndCreateMember err");
		}
		return false;
	}
	
	public Page<FuzionMember> listByPage(/*Map<String, Object> param,*/ HttpServletRequest request){
		Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
        String nickname = (String) param.get("nickname");
        if(StringUtils.isNotBlank(nickname)){//根据商家名称  模糊查询
            param.put("nickname", AceUtils.getPattern(nickname));
        }
        PageQueryParam<T> page = (PageQueryParam<T>) PageQueryUtils
                .preparePageQueryParam(request);

		/* 统计总数 */
        Iterator<String> ite = param.keySet().iterator();
        Query<FuzionMember> query = fuzionMemberService.getMongoDataSource2().createQuery(FuzionMember.class);
        while (ite.hasNext()) {
            String key = ite.next();
            Object value = param.get(key);
            if(key.endsWith("_contains")){
                key = key.replace("_contains", "");
                query.field(key).contains((String)value);
            }else{
                query = query.filter(key, value);
            }
        }
        final long count = fuzionMemberService.getMongoDataSource2().getCount(query);
        /* 返回列表 */
        final List<FuzionMember> list = query.order(page.getSortField())
                .offset(page.getPageIndex()).limit(page.getPageSize()).asList();
        
        //return new Page<T>(list, page.getPageIndex(), page.getPageSize(), count);
        //Page<FuzionMember> page2 = new Page<FuzionMember>(list, page.getPageIndex(), page.getPageSize(), count);
       
        if(list != null ){
        	list.forEach(pg -> {
				if(pg.getRecId() != null){//设置推荐人的名字
					FuzionMember fm = fuzionMemberService.getById(pg.getRecId());
					if(fm != null){
						String name = (StringUtils.isBlank(fm.getNickname()) ? fm.getUsername() : fm.getNickname());
						pg.setRecName(name);
					}
				}
				if(pg.getSellerId() != null){//设置会员所属的店铺名字
					Seller ss = sellerService.getById(pg.getSellerId());
					if(ss != null){
						pg.setSellerName(ss.getName());
					}
				}
			});
		}
		return new Page<FuzionMember>(list, page.getPageIndex(), page.getPageSize(), count);
		
		
		
		//Page<FuzionMember> page = fuzionMemberService.pageQuery(param, request);
		
	}
	
	/**
	 * 带有分页组装会员信息
	 * @param param
	 * @param request
	 * @return
	 */
	public Page<FuzionMember> listByPage2(Map<String, Object> param, HttpServletRequest request){
		Page<FuzionMember> page = fuzionMemberService.pageQuery(param, request);
		if(page != null && page.getData() != null){
			page.getData().forEach(pg -> {
				if(pg.getRecId() != null){//设置推荐人的名字
					FuzionMember fm = fuzionMemberService.getById(pg.getRecId());
					if(fm != null){
						String name = (StringUtils.isBlank(fm.getNickname()) ? fm.getUsername() : fm.getNickname());
						pg.setRecName(name);
					}
				}
				if(pg.getSellerId() != null){//设置会员所属的店铺名字
					Seller ss = sellerService.getById(pg.getSellerId());
					if(ss != null){
						pg.setSellerName(ss.getName());
					}
				}
			});
		}
		return page;
	}
	
	/**
	 * 扫描二维码时，新增或者修改大乱斗的会员信息
	 * @param member
	 */
	public void saveFuzionMember(FuzionMember member){
		logger.info("==============save member info======="+JSON.toJSONString(member));
		FuzionMember fmm = fuzionMemberService.getByField("openId", member.getOpenId());
		if(fmm != null){//如果是之前关注过的  暂时不做任何操作
			return ;
		}
		
		if(member.getRecId() != null){//有推荐人
			FuzionMember recMember = fuzionMemberService.getById(member.getRecId());
			if(recMember != null){//推荐人还存在
				member.setLevel(recMember.getLevel() + 1);
				member.setRecLevel(recMember.getLevel() + 1);
				member.setSellerId(recMember.getSellerId());//设置店铺ID
				member.setRecId(recMember.getId());
				fuzionMemberService.save(member);
				member.setPath(recMember.getPath() + member.getId() + FuzionConstants.Seller.SELLER_MEMBER_PATH);
				fuzionMemberService.update(member);
				logger.info("创建会员成功(有推荐人)：FuzionMember="+JSON.toJSONString(member));
			}else{//如果推荐人不存在  推送信息告知   推荐人失效  将推荐人暂时设置为店铺的会员
				Map<String, Object> sellerMember = Maps.newHashMapWithExpectedSize(2);
				sellerMember.put("weixinId", member.getWeixinId());
				sellerMember.put("type", FuzionConstants.Seller.SELLER_SELF_MEMBER);
				List<FuzionMember> fm = fuzionMemberService.list(sellerMember);
				if(!fm.isEmpty()){
					FuzionMember fmember = fm.get(0);//取店铺自己的会员ID
					member.setLevel(fmember.getLevel() + 1);
					member.setRecLevel(fmember.getLevel() + 1);
					member.setSellerId(fmember.getSellerId());//设置店铺ID
					member.setRecId(fmember.getId());//把推荐人设置成店铺自己
					fuzionMemberService.save(member);
					member.setPath(fmember.getPath() + member.getId() + FuzionConstants.Seller.SELLER_MEMBER_PATH);
					fuzionMemberService.update(member);
					logger.info("创建会员成功(推荐人失效，将推荐人暂时设置为店铺的会员)：FuzionMember="+JSON.toJSONString(member));
				}
			}
		}else{//没有推荐人   将推荐人暂时设置为店铺的会员
			Map<String, Object> sellerMember = Maps.newHashMapWithExpectedSize(2);
			sellerMember.put("weixinId", member.getWeixinId());
			sellerMember.put("type", FuzionConstants.Seller.SELLER_SELF_MEMBER);
			List<FuzionMember> fm = fuzionMemberService.list(sellerMember);
			if(!fm.isEmpty()){
				FuzionMember fmember = fm.get(0);//取店铺自己的会员ID
				member.setLevel(fmember.getLevel() + 1);
				member.setRecLevel(fmember.getLevel() + 1);
				member.setSellerId(fmember.getSellerId());//设置店铺ID
				member.setRecId(fmember.getId());//把推荐人设置成店铺自己
				fuzionMemberService.save(member);
				member.setPath(fmember.getPath() + member.getId() + FuzionConstants.Seller.SELLER_MEMBER_PATH);
				fuzionMemberService.update(member);
				logger.info("创建会员成功(没有推荐人，将推荐人暂时设置为店铺的会员)：FuzionMember="+JSON.toJSONString(member));
			}
		}
	}
}
